//
//  LSYUserAccountViewModel.swift
//  LSYWeibo
//
//  Created by 刘诗岩 on 16/4/13.
//  Copyright © 2016年 刘诗岩. All rights reserved.
//

import UIKit

class LSYUserAccountViewModel: NSObject {
    
    private let userInfoKey = "com.itheima.userinfokey"

    /// 单例对象
    static let sharedUserAccountViewModel: LSYUserAccountViewModel = LSYUserAccountViewModel()
    
    /// 用户账户模型
    var userAccount: LSYUserAccount?
    
    /// 添加一个计算性属性(只读属性)
    var userLogin: Bool {
        //1.UserAccount的token 如果不为空 && 用户token不过期 用户已经登录
        //  没有过期  -> 过期日期(2016.4.22) 和 当前日期(2016.4.11)比较  -> 过期日期大于 当前日期
        if let u = userAccount where u.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            
            return true
        }
        
        //将userAccount 设置为 nil
        userAccount = nil
        return false
    }
    
    /// 用户头像的 url
    var headImageURL: NSURL? {
        
        let url = NSURL(string: userAccount?.avatar_large ?? "")
        
        return url
    }
    
    private override init() {
        
        super.init()
        
        userAccount = self.loadUserInfo()
    }
}

// MARK: - 网络相关请求
extension LSYUserAccountViewModel{
    
    func loadAccessToken(code: String, finished: (isSuccess: Bool) -> ()){
        
        LSYNetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil {
                print(error)
                //TODO: 一会儿完善
                finished(isSuccess: false)
                return
            }
            //程序走到这里 就一定成功
            print("授权成功")
            //获取用户信息 在请求成功的回调中 再去获取用户信息
            self.loadUserInfo(result!, finished: finished)
        }
    }
    
    private func loadUserInfo(tokenResult: AnyObject, finished: (isSuccess: Bool) -> ()){
        
        // 看类型是否是字典类型
        guard let dic = tokenResult as? [String: AnyObject] else {
            
            finished(isSuccess: false)
            
            return
        }
        
        let token = dic["access_token"]!
        let uid = dic["uid"]!
        
        // 发送网络请求
        LSYNetworkTools.sharedTools.loadUserInfo(token, uid: uid) { (result, error) -> () in
            if error != nil{
                print(error)
                finished(isSuccess: false)
                return
            }
            
            // 看类型是否是字典类型
            guard var userInfoDic = token as? [String: AnyObject] else{
                finished(isSuccess: false)
                return
            }
            
            // 合并字典
            for (key,value) in dic{
                
                userInfoDic[key] = value
            }
            
            self.saveUserInfo(userInfoDic)
            
            finished(isSuccess: true)
        }
    }
}

// MARK - 存数,获取数据
extension LSYUserAccountViewModel{
    
    private func saveUserInfo(userInfoDic: [String: AnyObject]){
        
        let userDefaults = NSUserDefaults.standardUserDefaults()
        
        
        //给单例对象的用户账户模型属性赋值,为了解决从未登录状态到登录状态用户账户模型为空的问题
        let account = LSYUserAccount(dict: userInfoDic)
        self.userAccount = account
        
        //2.获取模型对象字典信息
        let keys = ["access_token","avatar_large","name","expires_in","uid","expires_date"]
        let accountDict = account.dictionaryWithValuesForKeys(keys)
        
        //3.将对象的字典信息保存到偏好设置中
        userDefaults.setObject(accountDict, forKey: userInfoKey)
        
        //4.同步
        userDefaults.synchronize()
    }
    
    //获取沙盒中存储的数据
    func loadUserInfo() -> LSYUserAccount? {
        //1.获取字典信息
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            return nil
        }
        //2.将字典转换为模型  命中缓存
        let account = LSYUserAccount(dict: dict)
        return account
    }
}










